package com.bbm.communitysystem.tools;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.generator.MathGenerator;
import cn.hutool.core.util.StrUtil;
import com.bbm.communitysystem.core.domain.Captcha;

public class ImgCaptcha {

    private static final int num = 1;

    public static Captcha generateCaptcha() {

        LineCaptcha captcha = CaptchaUtil.createLineCaptcha(200, 100);
        captcha.setGenerator(new MathGenerator(num));
        captcha.createCode();
        Captcha captcha1 = new Captcha();
        captcha1.setImg(captcha.getImageBase64Data());
        captcha1.setCode(captcha.getCode());
        captcha1.setKey(GetKey(captcha));
        return captcha1;
    }

    private static String GetKey(LineCaptcha captcha) {
        String code = captcha.getCode();
        int a = Integer.parseInt(StrUtil.sub(code, 0, num).trim());
        char operator = code.charAt(num);
        int b = Integer.parseInt(StrUtil.sub(code,  num + 1, num + 1 + num).trim());
        return switch (operator) {
            case '+' -> {
                System.out.println(a + b);
                yield String.valueOf(a + b);
            }
            case '-' -> String.valueOf(a - b);
            case '*' -> String.valueOf(a * b);
            default -> null;
        };
    }

}
